Sending http request | Post String data ( JSON ) | with authentication

Posted By : Akash Sharma | 17-Apr-2014

Recently I had a requirement where I had send http post request to a REST service which takes username and password for authentication and takes String data in the form of JSON.

 

Most of the examples I found on the internet were sending data as query string in post request.

 

NOTE :

The username and password for authentication are passed in header of request.The username and password data is first encrypted in Base64 and then added in Authorization header.

 

Let say I have a curl like this :

curl -H "Content-Type: application/json" -X POST  -u myusername:mypassword -d '{"name":"davy jones" , "email":"[email protected]"}' https://myApp.com/api/v1/json

 

Now I want equivalent equivalent java code for this using apache Http Client API.

Below is the code snippet for this.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

public class HttpPostReq
{
	public static void main(String args[])
	{
		String restUrl="https://myApp.com/api/v1/json";
		String username="myusername";
		String password="mypassword";
		JSONObject user=new JSONObject();
		user.put("name", "davy jones");
		user.put("email", "[email protected]");
		String jsonData=user.toString();
		HttpPostReq httpPostReq=new HttpPostReq();
		HttpPost httpPost=httpPostReq.createConnectivity(restUrl , username, password);
		httpPostReq.executeReq( jsonData, httpPost);
	}
	
	HttpPost createConnectivity(String restUrl, String username, String password)
	{
		HttpPost post = new HttpPost(restUrl);
		String auth=new StringBuffer(username).append(":").append(password).toString();
		byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
		String authHeader = "Basic " + new String(encodedAuth);
		post.setHeader("AUTHORIZATION", authHeader);
		post.setHeader("Content-Type", "application/json");
        	post.setHeader("Accept", "application/json");
        	post.setHeader("X-Stream" , "true");
		return post;
	}
	
	void executeReq(String jsonData, HttpPost httpPost)
	{
		try{
			executeHttpRequest(jsonData, httpPost);
		}
		catch (UnsupportedEncodingException e){
			System.out.println("error while encoding api url : "+e);
		}
		catch (IOException e){
			System.out.println("ioException occured while sending http request : "+e);
		}
		catch(Exception e){
			System.out.println("exception occured while sending http request : "+e);
		}
    	finally{
    		httpPost.releaseConnection();
    	}
	}
	
	void executeHttpRequest(String jsonData,  HttpPost httpPost)  throws UnsupportedEncodingException, IOException
	{
		HttpResponse response=null;
    	String line = "";
    	StringBuffer result = new StringBuffer();
    	httpPost.setEntity(new StringEntity(jsonData));
    	HttpClient client = HttpClientBuilder.create().build();
		response = client.execute(httpPost);
		System.out.println("Post parameters : " + jsonData );
		System.out.println("Response Code : " +response.getStatusLine().getStatusCode());
		BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		while ((line = reader.readLine()) != null){ result.append(line); }
		System.out.println(result.toString());
	}
}

 

Dependencies in pom.xml

<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.3</version>
</dependency>

 

 

Thanks

Akash Sharma

 

About Author

Author Image
Akash Sharma

Akash is a bright Groovy and Grails developer and have worked on development of various SaaS applications using Grails technologies. Akash loves playing Cricket and Tennis

Request for Proposal

Name is required

Comment is required

Sending message..